package cn.youframe.sample.db;

import cn.youframe.frame.base.BaseServiceImpl;
import cn.youframe.frame.exception.AppException;

import java.util.List;
import java.util.Map;

/**
 * User: Administrator
 * DateTime: 12-7-22 下午2:16
 * Desc:
 */
public class DBManagerServiceImpl extends BaseServiceImpl implements DBManagerService {
    public final static String TABLE_DESC="select COLUMN_NAME,TYPE_NAME,CHARACTER_MAXIMUM_LENGTH,NUMERIC_PRECISION,NUMERIC_SCALE,IS_NULLABLE,COLUMN_DEFAULT,REMARKS from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='PUBLIC' and TABLE_NAME=? ";
    public final static String TABLE_INDEXES="select TABLE_NAME,INDEX_NAME,COLUMN_NAME,ORDINAL_POSITION,INDEX_TYPE_NAME,NON_UNIQUE from INFORMATION_SCHEMA.INDEXES where TABLE_SCHEMA='PUBLIC' and TABLE_NAME=? order by INDEX_NAME,ORDINAL_POSITION";
    private DBManagerDao dbManagerDao;

    public DBManagerDao getDbManagerDao() {
        return dbManagerDao;
    }

    @Override
    public int execUpdate(String sql) {
        int ret=-1;
        try{
            ret=dbManagerDao.execUpdate(sql);
        }catch (Exception e){
            throw new AppException(e,"执行数据库更新异常："+e.getMessage());
        }
        return ret;
    }

    @Override
    public List<String> getTables() {
        return dbManagerDao.getTables();
    }

    @Override
    public List<Map<String,Object>> query(String sql, String execType) {
        List<Map<String,Object>> list=null;
        if(execType.equalsIgnoreCase("0")){
            list=dbManagerDao.query(sql);
        }else if(execType.equalsIgnoreCase("1")){
            list=dbManagerDao.queryTable(TABLE_DESC,sql);
        }else if(execType.equalsIgnoreCase("2")){
            list=dbManagerDao.queryTable(TABLE_INDEXES,sql);
        }
        return list;
    }

    public void setDbManagerDao(DBManagerDao dbManagerDao) {
        this.dbManagerDao = dbManagerDao;
    }
}
